package org.example.seata.bs.auth.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.example.seata.common.core.util.ApiResp;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Map;

/**
 * @author hzq
 * @date 2021/12/10 15:57
 */
@Api(tags = "认证中心")
@RestController
@AllArgsConstructor
public class TokenController {

    private final TokenEndpoint tokenEndpoint;

    @ApiOperation("认证")
    @RequestMapping(value = "/oauth/token", method = RequestMethod.GET)
    public ApiResp<OAuth2AccessToken> getAccessToken(Principal principal, @RequestParam
            Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        ResponseEntity<OAuth2AccessToken> accessToken = tokenEndpoint.getAccessToken(principal, parameters);
        return ApiResp.ofSuccess(accessToken.getBody());
    }

    @ApiOperation("认证")
    @RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
    public ApiResp<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
            Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        ResponseEntity<OAuth2AccessToken> accessToken = tokenEndpoint.postAccessToken(principal, parameters);
        return ApiResp.ofSuccess(accessToken.getBody());
    }
}
